package main

import (
	list2 "container/list"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"local_server/db"
	"local_server/utils"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
)

//type HttpData struct {
//	Code int         `json:"code"`
//	Data interface{} `json:"data"`
//}

var rootPath string

func main() {
	utils.PrintIP()
	rootPath = filepath.Dir(os.Args[0])
	println(rootPath)
	var config = utils.GetIpAndPort(rootPath)
	router := gin.Default()
	router.Static("/file", rootPath)

	router.GET("/recommend", GetRecommendApi)
	router.GET("/list", GetListApi)
	router.GET("/tv/detail", GetTvDetailApi)
	router.Run(":" + strconv.Itoa(config.Port))
}

// 获取列表 参数 start 数量 len 种类 type
func GetListApi(context *gin.Context) {
	start := context.Query("start")
	length := context.Query("len")
	ty := context.Query("type")
	println(start)
	println(length)
	println(ty)

	if start == "" || length == "" || ty == "" {
		utils.ReturnLogicErr(context, 400, "参数错误")
		return
	}
	s, e := strconv.Atoi(start)
	if e != nil {
		utils.ReturnLogicErr(context, 400, "参数错误")
		return
	}
	l, e := strconv.Atoi(length)
	if e != nil {
		utils.ReturnLogicErr(context, 400, "参数错误")
		return
	}

	t, e := strconv.Atoi(ty)
	if e != nil {
		utils.ReturnLogicErr(context, 400, "参数错误")
		return
	}

	content := db.GetList(t, s, l)
	c := db.GetCount(t)
	var d = make(map[string]interface{})
	d["count"] = c
	d["content"] = getMediaArray(content)
	context.JSON(http.StatusOK, utils.HttpData{
		Code: http.StatusOK,
		Data: d,
	})
}

// 推荐列表
func GetRecommendApi(context *gin.Context) {
	println("start")
	data := db.GetRecommendList()
	println(data[0])
	println(data[1])
	var mapData = make(map[string]interface{})
	mapData["film"] = getMediaArray(data[0])
	mapData["tv"] = getMediaArray(data[1])
	mapData["anim"] = getMediaArray(data[2])
	mapData["zongyi"] = getMediaArray(data[3])
	mapData["record"] = getMediaArray(data[4])
	context.JSON(http.StatusOK, utils.HttpData{
		Code: http.StatusOK,
		Data: mapData,
	})
}

func GetTvDetailApi(context *gin.Context) {
	path := rootPath + context.Query("path")
	arr, e := ioutil.ReadDir(path)
	if utils.ReturnError(e, context, 400, "读取文件夹错误") {
		return
	}

	var list = list2.New()
	for _, fileInfo := range arr {
		if utils.IsValidMediaFile(fileInfo) {
			list.PushBack(fileInfo)
		}
	}
	var sortedList = utils.SortFile(list)
	var data = make([]string, sortedList.Len())
	var i = 0
	for e := sortedList.Front(); e != nil; e = e.Next() {
		data[i] = e.Value.(string)
		fmt.Println(data[i])
		i += 1
	}

	context.JSON(http.StatusOK, utils.HttpData{
		Code: http.StatusOK,
		Data: data,
	})

}

func getMediaArray(s string) []db.MediaInfo {
	var film []db.MediaInfo
	e := json.Unmarshal([]byte(s), &film)
	utils.CheckErr(e)
	return film
}
